<template>
  <a-card :bordered="false">
    <!-- 统计分析区域 -->
    <transition name="fade">
      <div class="statistics-area" v-if="showStatisticsArea">
        <a-row>
          <a-col :span="24">
            <div class="statistics-header">
              <h3>库存历史统计分析</h3>
              <div class="statistics-controls">
                <a-radio-group
                  v-model="statisticsTimeRange"
                  button-style="solid"
                  @change="handleTimeRangeChange"
                  size="small"
                >
                  <a-radio-button value="week">近七天</a-radio-button>
                  <a-radio-button value="month">近一月</a-radio-button>
                  <a-radio-button value="year">近一年</a-radio-button>
                </a-radio-group>
                <a-button icon="reload" style="margin-left: 8px" @click="refreshStatistics"></a-button>
                <a-button icon="close" type="link" @click="hideStatistics" />
              </div>
            </div>
          </a-col>
        </a-row>

        <a-row :gutter="16" style="margin-top: 8px">
          <!-- 业务类型分布 -->
          <a-col :xl="8" :lg="8" :md="12" :sm="24" :xs="24">
            <div class="chart-card">
              <div class="chart-card-title">
                业务类型分布
                <span class="chart-card-subtitle">{{ getTimeRangeText() }}</span>
              </div>
              <div class="chart-container-wrapper">
                <div
                  style="height: 100%; width: 100%"
                  :id="chartIds.businessType"
                  class="chart-container"
                  aria-hidden="false"
                ></div>
              </div>
            </div>
          </a-col>

          <!-- 物料类型分布 -->
          <a-col :xl="8" :lg="8" :md="12" :sm="24" :xs="24">
            <div class="chart-card">
              <div class="chart-card-title">
                物料类型分布
                <span class="chart-card-subtitle">{{ getTimeRangeText() }}</span>
              </div>
              <div class="chart-container-wrapper">
                <div
                  style="height: 100%; width: 100%"
                  :id="chartIds.materialType"
                  class="chart-container"
                  aria-hidden="false"
                ></div>
              </div>
            </div>
          </a-col>

          <!-- 时间趋势 -->
          <a-col :xl="8" :lg="8" :md="24" :sm="24" :xs="24">
            <div class="chart-card">
              <div class="chart-card-title">
                时间趋势
                <span class="chart-card-subtitle">{{ getTimeRangeText() }}</span>
              </div>
              <div class="chart-container-wrapper">
                <div
                  style="height: 100%; width: 100%"
                  :id="chartIds.timeChart"
                  class="chart-container"
                  aria-hidden="false"
                ></div>
              </div>
            </div>
          </a-col>
        </a-row>
      </div>
    </transition>

    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :md="6" :sm="8">
            <a-form-item label="物料类型">
              <j-dict-select-tag
                placeholder="请选择物料类型"
                v-model="queryParam.materialType"
                dictCode="material_type"
                @change="handleMaterialTypeChange"
                allowClear
              />
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="8">
            <a-form-item label="物料编号">
              <a-input placeholder="请输入物料编号" v-model="queryParam.materialCode" allowClear />
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="8">
            <a-form-item label="系列">
              <a-input placeholder="请输入系列" v-model="queryParam.materialSeries" allowClear />
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="8">
            <a-form-item label="颜色">
              <a-input placeholder="请输入颜色" v-model="queryParam.color" allowClear />
            </a-form-item>
          </a-col>
          <template v-if="!toggleSearchStatus">
            <a-col :md="6" :sm="8">
              <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
                <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
                <a-button style="margin-left: 8px" @click="searchReset" icon="reload">重置</a-button>
                <a @click="handleToggleSearch" style="margin-left: 8px">
                  {{ toggleSearchStatus ? '收起' : '展开' }}
                  <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
                </a>
              </span>
            </a-col>
          </template>
          <template v-if="toggleSearchStatus">
            <a-col :md="6" :sm="8">
              <a-form-item label="仓库">
                <j-select-warehouse
                  placeholder="请选择仓库"
                  v-model="queryParam.warehouseId"
                  @change="handleWarehouseChange"
                  allowClear
                />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="8">
              <a-form-item label="库位">
                <j-select-warehouse-location
                  placeholder="请选择库位"
                  v-model="queryParam.locationId"
                  :warehouse-id="warehouseId"
                  allowClear
                />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="8">
              <a-form-item label="业务类型">
                <j-dict-select-tag
                  placeholder="请选择业务类型"
                  v-model="queryParam.businessType"
                  dictCode="inventory_business_type"
                  allowClear
                />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="8">
              <a-form-item label="批次号">
                <a-input placeholder="请输入批次号" v-model="queryParam.batchNo" allowClear></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="8">
              <a-form-item label="业务单号">
                <a-input placeholder="请输入业务单号" v-model="queryParam.businessNo" allowClear></a-input>
              </a-form-item>
            </a-col>
            <!-- 移除操作人查询条件 -->
            <a-col :xl="10" :lg="11" :md="12" :sm="24">
              <a-form-item label="操作时间">
                <a-range-picker
                  style="width: 100%"
                  v-model="operateTimeRange"
                  format="YYYY-MM-DD"
                  :placeholder="['开始日期', '结束日期']"
                  @change="onOperateTimeChange"
                  allowClear
                />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="8">
              <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
                <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
                <a-button style="margin-left: 8px" @click="searchReset" icon="reload">重置</a-button>
                <a @click="handleToggleSearch" style="margin-left: 8px">
                  {{ toggleSearchStatus ? '收起' : '展开' }}
                  <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
                </a>
              </span>
            </a-col>
          </template>
        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button
        type="primary"
        icon="download"
        @click="handleExport"
        :disabled="!hasPermission('wms:inventoryHistory:export')"
        >导出</a-button
      >
      <a-button
        :icon="showStatisticsArea ? 'eye-invisible' : 'bar-chart'"
        @click="toggleStatistics"
        style="margin-left: 8px"
      >
        {{ showStatisticsArea ? '隐藏统计分析' : '显示统计分析' }}
      </a-button>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
        <a style="font-weight: 600">{{ selectedRowKeys.length }}</a
        >项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        :scroll="{ x: 1800, y: 500 }"
        @change="handleTableChange"
      >
        <template slot="materialTypeSlot" slot-scope="text">
          <a-tag :color="getMaterialTypeColor(text)">
            <j-dict-label :value="text" dictCode="material_type" />
          </a-tag>
        </template>

        <template slot="businessTypeSlot" slot-scope="text">
          <a-tag :color="getBusinessTypeColor(text)">
            {{ getBusinessTypeName(text) }}
          </a-tag>
        </template>

        <template slot="changeQuantitySlot" slot-scope="text">
          <span :style="{ color: getQuantityColor(text) }">{{ text }}</span>
        </template>

        <template slot="operateTimeSlot" slot-scope="text">
          <span>{{ text ? formatDateTime(text) : '-' }}</span>
        </template>
      </a-table>
    </div>
    <!-- table区域-end -->
  </a-card>
</template>

<script>
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import JDictSelectTag from '@/components/dict/JDictSelectTag'
import JDictLabel from '@/components/dict/JDictLabel'
import JSelectMaterial from '@/components/jeecgbiz/JSelectMaterial'
import JSelectWarehouse from '@/components/jeecgbiz/JSelectWarehouse'
import JSelectWarehouseLocation from '@/components/jeecgbiz/JSelectWarehouseLocation'
import JDate from '@/components/jeecg/JDate'
import { downFile } from '@/api/manage'
import moment from 'moment'
import { USER_AUTH, SYS_BUTTON_AUTH } from '@/store/mutation-types'
import * as echarts from 'echarts'

export default {
  name: 'InventoryHistoryList',
  mixins: [JeecgListMixin],
  components: {
    JDictSelectTag,
    JDictLabel,
    JSelectMaterial,
    JSelectWarehouse,
    JSelectWarehouseLocation,
    JDate,
  },
  data() {
    return {
      description: '库存历史记录',
      // 查询条件
      queryParam: {
        materialCode: '',
        materialName: '',
        materialType: '',
        materialSeries: '',
        color: '',
        warehouseId: '',
        locationId: '',
        businessType: '',
        businessNo: '',
        batchNo: '',
        // 移除 operator
        operateTime: '',
        operateTimeStart: '',
        operateTimeEnd: '',
        beginDate: '', // 新增
        endDate: '', // 新增
      },
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '物料编号',
          align: 'center',
          dataIndex: 'materialCode',
          width: 120,
        },
        {
          title: '物料名称',
          align: 'center',
          dataIndex: 'materialName',
          width: 150,
        },
        {
          title: '系列',
          align: 'center',
          dataIndex: 'materialSeries',
          width: 150,
        },
        {
          title: '颜色',
          align: 'center',
          dataIndex: 'color',
          width: 150,
        },
        {
          title: '物料类型',
          align: 'center',
          dataIndex: 'materialType',
          width: 100,
          scopedSlots: { customRender: 'materialTypeSlot' },
        },
        {
          title: '仓库',
          align: 'center',
          dataIndex: 'warehouseName',
          width: 120,
        },
        {
          title: '库位',
          align: 'center',
          dataIndex: 'locationName',
          width: 120,
        },
        {
          title: '业务类型',
          align: 'center',
          dataIndex: 'businessType',
          width: 100,
          scopedSlots: { customRender: 'businessTypeSlot' },
        },
        {
          title: '业务单号',
          align: 'center',
          dataIndex: 'businessNo',
          width: 150,
        },
        {
          title: '变更前数量',
          align: 'center',
          dataIndex: 'beforeQuantity',
          width: 100,
        },
        {
          title: '变更数量',
          align: 'center',
          dataIndex: 'changeQuantity',
          width: 100,
          scopedSlots: { customRender: 'changeQuantitySlot' },
        },
        {
          title: '变更后数量',
          align: 'center',
          dataIndex: 'afterQuantity',
          width: 100,
        },
        {
          title: '单位成本',
          align: 'center',
          dataIndex: 'unitCost',
          width: 100,
          customRender: (text) => {
            return text ? '¥' + parseFloat(text).toFixed(2) : '¥0.00'
          },
        },
        {
          title: '变动前总成本',
          align: 'center',
          dataIndex: 'beforeTotalCost',
          width: 120,
          customRender: (text) => {
            return text ? '¥' + parseFloat(text).toFixed(2) : '¥0.00'
          },
        },
        {
          title: '成本变动金额',
          align: 'center',
          dataIndex: 'changeTotalCost',
          width: 120,
          customRender: (text) => {
            return text ? '¥' + parseFloat(text).toFixed(2) : '¥0.00'
          },
        },
        {
          title: '变动后总成本',
          align: 'center',
          dataIndex: 'afterTotalCost',
          width: 120,
          customRender: (text) => {
            return text ? '¥' + parseFloat(text).toFixed(2) : '¥0.00'
          },
        },
        {
          title: '批次号',
          align: 'center',
          dataIndex: 'batchNo',
          width: 120,
        },
        {
          title: '操作人',
          align: 'center',
          dataIndex: 'operator',
          width: 100,
        },
        {
          title: '操作时间',
          align: 'center',
          dataIndex: 'operateTime',
          width: 150,
          scopedSlots: { customRender: 'operateTimeSlot' },
        },
        {
          title: '备注',
          align: 'center',
          dataIndex: 'remark',
          width: 150,
        },
      ],
      url: {
        list: '/wms/inventoryHistory/list',
        exportXlsUrl: '/wms/inventoryHistory/exportXls',
      },
      warehouseId: '',
      materialType: '',
      operateTimeRange: [], // 新增操作时间范围
      // 权限相关
      permissionList: [],
      showStatisticsArea: false, // 控制统计分析区域显示/隐藏
      toggleSearchStatus: false, // 控制查询区域的展开/收起状态
      // 图表实例
      charts: {
        businessTypeChart: null,
        materialTypeChart: null,
        timeChart: null,
      },
      // 图表容器ID
      chartIds: {
        businessType: '',
        materialType: '',
        timeChart: '',
      },
      // 统计时间范围
      statisticsTimeRange: 'week', // 默认显示当日
      // 统计图表数据
      statisticsData: {
        businessTypeStats: [],
        materialTypeStats: [],
        timeStats: [],
      },
    }
  },
  created() {
    // 加载字典数据
    this.initDictConfig()

    // 加载权限
    this.loadPermissions()

    // 页面加载时重置查询条件
    this.searchReset()

    // 默认不显示统计区域
    this.showStatisticsArea = false

    // 初始化图表容器ID
    this.chartIds = {
      businessType: 'businessTypeChart_' + this._uid,
      materialType: 'materialTypeChart_' + this._uid,
      timeChart: 'timeChart_' + this._uid,
    }
  },

  mounted() {
    // 添加窗口大小变化事件监听
    window.addEventListener('resize', this.resizeCharts)

    // 如果默认显示统计区域，则初始化图表
    if (this.showStatisticsArea) {
      this.$nextTick(() => {
        this.loadStatisticsData()
      })
    }
  },

  beforeDestroy() {
    // 移除窗口大小变化事件监听
    window.removeEventListener('resize', this.resizeCharts)

    // 确保销毁所有图表实例
    try {
      if (this.charts.businessTypeChart) {
        this.charts.businessTypeChart.dispose()
        this.charts.businessTypeChart = null
      }
      if (this.charts.materialTypeChart) {
        this.charts.materialTypeChart.dispose()
        this.charts.materialTypeChart = null
      }
      if (this.charts.timeChart) {
        this.charts.timeChart.dispose()
        this.charts.timeChart = null
      }
    } catch (error) {
      console.error('组件销毁时清理图表实例失败:', error)
    }
  },
  methods: {
    // 加载权限
    loadPermissions() {
      // 从sessionStorage获取权限
      let authList = JSON.parse(sessionStorage.getItem(USER_AUTH) || '[]')

      // 如果sessionStorage中没有权限，尝试从localStorage获取
      if (!authList || authList.length === 0) {
        authList = JSON.parse(localStorage.getItem(USER_AUTH) || '[]')
      }

      // 从按钮权限中获取
      const buttonAuth = JSON.parse(
        sessionStorage.getItem(SYS_BUTTON_AUTH) || localStorage.getItem(SYS_BUTTON_AUTH) || '[]'
      )

      // 合并权限
      if (buttonAuth && buttonAuth.length > 0) {
        authList = authList.concat(buttonAuth)
      }

      // 临时添加WMS相关权限用于测试
      const testPermissions = [{ action: 'wms:inventoryHistory:export' }]
      authList = authList.concat(testPermissions)

      // 提取action字段
      this.permissionList = authList.map((auth) => auth.action || auth)
    },

    // 判断是否有权限
    hasPermission(permission) {
      if (!permission) return true // 如果未指定权限，默认有权限

      // 检查权限列表中是否包含指定权限
      if (this.permissionList.includes(permission)) {
        return true
      }

      // 检查权限列表中是否包含以逗号分隔的多个权限
      for (let perm of this.permissionList) {
        if (perm && perm.includes(',')) {
          const perms = perm.split(',')
          if (perms.includes(permission)) {
            return true
          }
        }
      }

      return false
    },

    // 处理物料类型变化
    handleMaterialTypeChange(value) {
      this.materialType = value
      this.queryParam.materialCode = ''
    },

    // 处理物料变化
    handleMaterialChange(value, materials) {
      if (materials && materials.length > 0) {
        const material = materials[0]
        this.queryParam.materialName = material.materialName
      } else {
        this.queryParam.materialName = ''
      }
    },

    // 处理仓库变化
    handleWarehouseChange(value) {
      this.warehouseId = value
      this.queryParam.locationId = ''
    },

    // 重写searchReset方法，确保重置所有查询条件
    searchReset() {
      this.queryParam = {
        materialCode: '',
        materialName: '',
        materialType: '',
        materialSeries: '',
        color: '',
        warehouseId: '',
        locationId: '',
        businessType: '',
        businessNo: '',
        batchNo: '',
        // 移除 operator
        operateTime: '',
        operateTimeStart: '',
        operateTimeEnd: '',
        beginDate: '',
        endDate: '',
      }
      this.materialType = ''
      this.warehouseId = ''
      this.operateTimeRange = []
      this.loadData(1)
    },

    // 重写getQueryParams方法，处理日期格式
    getQueryParams() {
      let params = Object.assign({}, this.$data.queryParam)

      // 处理日期范围
      if (this.operateTimeRange && this.operateTimeRange.length === 2) {
        params.operateTimeStart = this.operateTimeRange[0].format('YYYY-MM-DD 00:00:00')
        params.operateTimeEnd = this.operateTimeRange[1].format('YYYY-MM-DD 23:59:59')

        // 设置beginDate和endDate，适配后端接口变化
        params.beginDate = params.operateTimeStart
        params.endDate = params.operateTimeEnd

        // 删除operateTime参数，避免冲突
        delete params.operateTime
      } else {
        // 如果没有选择日期范围，确保清空相关参数
        params.operateTimeStart = ''
        params.operateTimeEnd = ''
        params.beginDate = ''
        params.endDate = ''
        delete params.operateTime
      }

      // 分页参数
      params.pageNo = this.ipagination.current
      params.pageSize = this.ipagination.pageSize

      return params
    },

    // 处理操作时间变化
    onOperateTimeChange(date, dateString) {
      if (date && date.length === 2) {
        this.queryParam.operateTimeStart = date[0].format('YYYY-MM-DD 00:00:00')
        this.queryParam.operateTimeEnd = date[1].format('YYYY-MM-DD 23:59:59')

        // 设置beginDate和endDate，适配后端接口变化
        this.queryParam.beginDate = this.queryParam.operateTimeStart
        this.queryParam.endDate = this.queryParam.operateTimeEnd

        // 清空operateTime参数，避免冲突
        this.queryParam.operateTime = ''
      } else {
        this.queryParam.operateTimeStart = ''
        this.queryParam.operateTimeEnd = ''
        this.queryParam.beginDate = ''
        this.queryParam.endDate = ''
        this.queryParam.operateTime = ''
      }
    },

    // 导出
    handleExport() {
      let params = this.getQueryParams()

      // 调用导出接口
      this.loading = true
      downFile(this.url.exportXlsUrl, params)
        .then((data) => {
          if (!data) {
            this.$message.warning('文件下载失败')
            return
          }
          if (typeof window.navigator.msSaveBlob !== 'undefined') {
            window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), '库存历史记录.xls')
          } else {
            let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
            let link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            link.setAttribute('download', '库存历史记录.xls')
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link) // 下载完成移除元素
            window.URL.revokeObjectURL(url) // 释放掉blob对象
          }
        })
        .finally(() => {
          this.loading = false
        })
    },

    // 格式化日期时间
    formatDateTime(timestamp) {
      return moment(timestamp).format('YYYY-MM-DD HH:mm:ss')
    },

    // 获取物料类型颜色
    getMaterialTypeColor(type) {
      // 确保type为数字类型
      const typeNum = parseInt(type)
      switch (typeNum) {
        case 1:
          return 'blue'
        case 2:
          return 'green'
        case 3:
          return 'purple'
        case 4:
          return 'orange'
        case 5:
          return 'red'
        case 6:
          return 'yellow'
      }
    },

    // 获取业务类型名称
    getBusinessTypeName(type) {
      const typeNum = parseInt(type)
      switch (typeNum) {
        case 11:
          return '采购入库'
        case 12:
          return '生产余料入库'
        case 13:
          return '仓库调拨入库'
        case 19:
          return '其它入库'
        case 21:
          return '生产领料'
        case 22:
          return '调拨出库'
        case 23:
          return '销售出库'
        case 29:
          return '其他出库'
        default:
          return '未知类型'
      }
    },

    // 获取业务类型颜色 入库同颜色 出库同颜色 其他同颜色
    // 采购入库	11
    // 生产余料入库	12
    // 仓库调拨入库	13
    // 其他入库	19
    // 生产领料出库	21
    // 仓库调拨出库	22
    // 销售出库	23
    // 其他出库	29
    //库存调整 30
    //盘点 40
    getBusinessTypeColor(type) {
      const typeNum = parseInt(type)
      switch (typeNum) {
        case 11:
        case 12:
        case 13:
        case 19:
          return 'green'
        case 21:
        case 22:
        case 23:
        case 29:
          return 'red'
        case 30:
          return 'blue'
        case 40:
          return 'purple'
        default:
          return 'gray'
      }
    },

    // 获取数量颜色
    getQuantityColor(quantity) {
      if (quantity > 0) {
        return '#52c41a' // 绿色
      } else if (quantity < 0) {
        return '#f5222d' // 红色
      } else {
        return '#595959' // 灰色
      }
    },

    // 切换查询区域展开/收起
    handleToggleSearch() {
      this.toggleSearchStatus = !this.toggleSearchStatus
    },

    // 显示统计分析区域
    showStatistics() {
      // 先设置状态为显示
      this.showStatisticsArea = true

      // 使用nextTick确保DOM已更新
      this.$nextTick(() => {
        // 加载统计数据
        this.loadStatisticsData()
      })
    },

    // 加载统计数据
    loadStatisticsData() {
      // 显示加载状态
      this.loading = true

      // 构建查询参数
      const params = {
        timeRange: this.statisticsTimeRange,
        materialType: this.queryParam.materialType || '',
        materialCode: this.queryParam.materialCode || '',
        warehouseId: this.queryParam.warehouseId || '',
        locationId: this.queryParam.locationId || '',
        businessType: this.queryParam.businessType || '',
        businessNo: this.queryParam.businessNo || '',
      }

      console.log('加载统计数据，时间范围:', this.statisticsTimeRange)

      // 调用后端接口获取统计数据
      return this.$http
        .get('/wms/inventoryHistory/getStatisticsData', { params })
        .then((res) => {
          if (res.success) {
            // 保存统计数据
            this.statisticsData = res.result

            // 使用多层nextTick和更长的延迟确保DOM完全渲染
            this.$nextTick(() => {
              // 第一次延迟，等待DOM更新
              setTimeout(() => {
                this.$nextTick(() => {
                  // 第二次延迟，确保DOM完全渲染
                  setTimeout(() => {
                    this.initCharts()
                  }, 500)
                })
              }, 200)
            })
          } else {
            this.$message.warning(res.message || '获取统计数据失败')
          }
        })
        .catch((err) => {
          console.error('获取统计数据失败', err)
          this.$message.error('获取统计数据失败')
        })
        .finally(() => {
          this.loading = false
        })
    },

    // 隐藏统计分析区域
    hideStatistics() {
      this.showStatisticsArea = false

      // 延迟销毁图表实例，等待动画完成
      setTimeout(() => {
        try {
          if (this.charts.businessTypeChart) {
            this.charts.businessTypeChart.dispose()
            this.charts.businessTypeChart = null
          }
          if (this.charts.materialTypeChart) {
            this.charts.materialTypeChart.dispose()
            this.charts.materialTypeChart = null
          }
          if (this.charts.timeChart) {
            this.charts.timeChart.dispose()
            this.charts.timeChart = null
          }
        } catch (error) {
          console.error('销毁图表实例失败:', error)
          // 确保图表实例被清空
          this.charts.businessTypeChart = null
          this.charts.materialTypeChart = null
          this.charts.timeChart = null
        }
      }, 300)
    },

    // 切换统计分析弹窗的显示/隐藏
    toggleStatistics() {
      if (this.showStatisticsArea) {
        this.hideStatistics()
      } else {
        this.showStatistics()
      }
    },

    // 初始化统计图表
    initCharts() {
      try {
        console.log('开始初始化图表...')

        // 初始化业务类型分布图表
        this.initBusinessTypeChart()

        // 初始化物料类型分布图表
        this.initMaterialTypeChart()

        // 初始化时间趋势图表
        this.initTimeChart()

        // 窗口大小变化时重新调整图表大小
        window.removeEventListener('resize', this.resizeCharts) // 先移除之前的监听
        window.addEventListener('resize', this.resizeCharts)

        console.log('图表初始化完成')
      } catch (error) {
        console.error('初始化图表失败:', error)
      }
    },

    // 初始化业务类型分布图表
    initBusinessTypeChart() {
      try {
        console.log('初始化业务类型图表...')

        // 检查DOM元素是否存在
        const businessTypeChartDom = document.getElementById(this.chartIds.businessType)
        if (!businessTypeChartDom) {
          console.error('业务类型图表DOM元素不存在')
          return
        }

        // 清除之前的图表实例
        if (this.charts.businessTypeChart) {
          this.charts.businessTypeChart.dispose()
          this.charts.businessTypeChart = null
        }

        // 检查是否有统计数据
        if (!this.statisticsData || !this.statisticsData.businessTypeStats) {
          console.warn('没有可用的业务类型统计数据')
          return
        }

        // 业务类型分布数据处理
        const businessTypeData = this.statisticsData.businessTypeStats.map((item) => ({
          name: item.businessTypeName || '未知类型',
          value: parseFloat(item.totalQuantity || 0).toFixed(2),
          count: item.count || 0,
          itemStyle: {
            color: this.getBusinessTypeColor(item.businessType),
          },
        }))

        const businessTypeChart = echarts.init(businessTypeChartDom, null, {
          renderer: 'canvas',
        })
        businessTypeChart.setOption({
          title: {
            text: '',
            left: 'center',
          },
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)<br/>记录数: {c0}',
          },
          legend: {
            orient: 'vertical',
            left: 'left',
            data: businessTypeData.map((item) => item.name),
          },
          series: [
            {
              name: '业务类型',
              type: 'pie',
              radius: ['40%', '70%'],
              avoidLabelOverlap: false,
              label: {
                show: true,
                formatter: '{b}: {c} ({d}%)',
              },
              emphasis: {
                label: {
                  show: true,
                  fontSize: '18',
                  fontWeight: 'bold',
                },
              },
              labelLine: {
                show: true,
              },
              data: businessTypeData,
            },
          ],
        })
        this.charts.businessTypeChart = businessTypeChart
        console.log('业务类型图表初始化成功')
      } catch (err) {
        console.error('初始化业务类型图表失败:', err)
      }
    },

    // 初始化物料类型分布图表
    initMaterialTypeChart() {
      try {
        console.log('初始化物料类型图表...')

        // 检查DOM元素是否存在
        const materialTypeChartDom = document.getElementById(this.chartIds.materialType)
        if (!materialTypeChartDom) {
          console.error('物料类型图表DOM元素不存在')
          return
        }

        // 清除之前的图表实例
        if (this.charts.materialTypeChart) {
          this.charts.materialTypeChart.dispose()
          this.charts.materialTypeChart = null
        }

        // 检查是否有统计数据
        if (!this.statisticsData || !this.statisticsData.materialTypeStats) {
          console.warn('没有可用的物料类型统计数据')
          return
        }

        // 物料类型分布数据处理
        const materialTypeData = this.statisticsData.materialTypeStats.map((item) => ({
          name: item.materialTypeName || '未知类型',
          value: parseFloat(item.totalQuantity || 0).toFixed(2),
          count: item.count || 0,
          itemStyle: {
            color: this.getMaterialTypeColor(item.materialType),
          },
        }))

        const materialTypeChart = echarts.init(materialTypeChartDom, null, {
          renderer: 'canvas',
        })
        materialTypeChart.setOption({
          title: {
            text: '',
            left: 'center',
          },
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)<br/>记录数: {c0}',
          },
          legend: {
            orient: 'vertical',
            left: 'left',
            data: materialTypeData.map((item) => item.name),
          },
          series: [
            {
              name: '物料类型',
              type: 'pie',
              radius: ['40%', '70%'],
              avoidLabelOverlap: false,
              label: {
                show: true,
                formatter: '{b}: {c} ({d}%)',
              },
              emphasis: {
                label: {
                  show: true,
                  fontSize: '18',
                  fontWeight: 'bold',
                },
              },
              labelLine: {
                show: true,
              },
              data: materialTypeData,
            },
          ],
        })
        this.charts.materialTypeChart = materialTypeChart
        console.log('物料类型图表初始化成功')
      } catch (err) {
        console.error('初始化物料类型图表失败:', err)
      }
    },

    // 初始化时间趋势图表
    initTimeChart() {
      try {
        console.log('初始化时间趋势图表...')

        // 检查DOM元素是否存在
        const timeChartDom = document.getElementById(this.chartIds.timeChart)
        if (!timeChartDom) {
          console.error('时间趋势图表DOM元素不存在')
          return
        }

        // 清除之前的图表实例
        if (this.charts.timeChart) {
          this.charts.timeChart.dispose()
          this.charts.timeChart = null
        }

        // 检查是否有统计数据
        if (!this.statisticsData || !this.statisticsData.timeStats) {
          console.warn('没有可用的时间趋势统计数据')
          return
        }

        // 时间趋势数据处理
        const timeData = {
          dates: this.statisticsData.timeStats.map((item) => item.operateDate),
          inbound: this.statisticsData.timeStats.map((item) => parseFloat(item.inboundQuantity || 0).toFixed(2)),
          outbound: this.statisticsData.timeStats.map((item) => parseFloat(item.outboundQuantity || 0).toFixed(2)),
          adjust: this.statisticsData.timeStats.map((item) => parseFloat(item.adjustQuantity || 0).toFixed(2)),
        }

        const timeChart = echarts.init(timeChartDom, null, {
          renderer: 'canvas',
        })
        timeChart.setOption({
          title: {
            text: '',
            left: 'center',
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow',
            },
          },
          legend: {
            data: ['入库', '出库', '调整'],
            top: 30,
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true,
          },
          xAxis: {
            type: 'category',
            data: timeData.dates,
          },
          yAxis: {
            type: 'value',
            name: '数量',
          },
          series: [
            {
              name: '入库',
              type: 'bar',
              stack: 'total',
              itemStyle: {
                color: '#52c41a',
              },
              emphasis: {
                focus: 'series',
              },
              data: timeData.inbound,
            },
            {
              name: '出库',
              type: 'bar',
              stack: 'total',
              itemStyle: {
                color: '#f5222d',
              },
              emphasis: {
                focus: 'series',
              },
              data: timeData.outbound,
            },
            {
              name: '调整',
              type: 'bar',
              stack: 'total',
              itemStyle: {
                color: '#1890ff',
              },
              emphasis: {
                focus: 'series',
              },
              data: timeData.adjust,
            },
          ],
        })
        this.charts.timeChart = timeChart
        console.log('时间趋势图表初始化成功')
      } catch (err) {
        console.error('初始化时间趋势图表失败:', err)
      }
    },

    // 重新调整图表大小
    resizeCharts() {
      if (!this.showStatisticsArea) return

      try {
        if (this.charts.businessTypeChart) this.charts.businessTypeChart.resize()
        if (this.charts.materialTypeChart) this.charts.materialTypeChart.resize()
        if (this.charts.timeChart) this.charts.timeChart.resize()
      } catch (error) {
        console.error('调整图表大小失败:', error)
      }
    },

    // 获取物料类型名称
    getMaterialTypeName(type) {
      const typeNum = parseInt(type)
      switch (typeNum) {
        case 1:
          return '型材'
        case 2:
          return '配件'
        case 3:
          return '辅件'
        case 4:
          return '其他'
        case 5:
          return '余料'
        case 6:
          return '半料'
        default:
          return '未知类型'
      }
    },

    // 获取时间范围文本
    getTimeRangeText() {
      switch (this.statisticsTimeRange) {
        case 'week':
          return '(近七天)'
        case 'month':
          return '(近一月)'
        case 'year':
          return '(近一年)'
        default:
          return ''
      }
    },

    // 重写loadData方法，添加图表刷新逻辑
    loadData(arg) {
      if (arg === 1) {
        this.ipagination.current = 1
      }
      const params = this.getQueryParams()
      this.loading = true
      this.$http
        .get(this.url.list, { params })
        .then((res) => {
          if (res.success) {
            this.dataSource = res.result.records
            this.ipagination.total = res.result.total

            // 如果统计区域显示中，刷新统计数据
            if (this.showStatisticsArea) {
              this.loadStatisticsData()
            }
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },

    // 刷新统计数据
    refreshStatistics() {
      if (this.showStatisticsArea) {
        // 显示加载状态
        this.$message.loading({ content: '正在刷新统计数据...', duration: 0, key: 'statsLoading' })

        // 加载统计数据
        this.loadStatisticsData()
          .then(() => {
            // 关闭加载提示
            this.$message.success({ content: '统计数据已更新', key: 'statsLoading', duration: 2 })
          })
          .catch(() => {
            // 关闭加载提示
            this.$message.error({ content: '统计数据更新失败', key: 'statsLoading', duration: 2 })
          })
      }
    },

    // 处理时间范围变化
    handleTimeRangeChange(e) {
      this.statisticsTimeRange = e.target.value
      this.refreshStatistics()
    },
  },
}
</script>

<style scoped>
@import '~@assets/less/common.less';

/* 查询区域样式 */
.table-page-search-wrapper {
  margin-bottom: 16px;
  background-color: #fff;
  padding: 16px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.table-page-search-wrapper .ant-form-item {
  margin-bottom: 12px;
}

/* 操作按钮区域样式 */
.table-operator {
  margin-bottom: 16px;
  background-color: #fff;
  padding: 10px 16px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

/* 表格区域样式 */
.ant-card-body {
  padding: 12px !important;
}

.ant-alert {
  margin-bottom: 12px !important;
}

.ant-table-thead > tr > th {
  background-color: #f5f7fa !important;
  font-weight: 600;
  color: #303133;
}

.ant-table-tbody > tr:hover > td {
  background-color: #e6f7ff !important;
}

/* 自定义颜色样式 */
.positive-amount {
  color: #52c41a;
  font-weight: 500;
}

.negative-amount {
  color: #f5222d;
  font-weight: 500;
}

/* 统计分析弹窗样式 */
.statistics-modal .ant-modal-body {
  padding: 0;
}

.statistics-modal .ant-tabs-tabpane {
  padding: 16px;
}

.statistics-modal .ant-tabs-bar {
  margin-bottom: 0;
  padding: 8px 0;
}

/* 图表容器样式 */
.chart-container {
  position: relative;
  overflow: hidden;
  background-color: transparent;
  height: 100%;
  width: 100%;
}

.chart-container-wrapper {
  width: 100%;
  height: 100%;
  padding: 8px;
  box-sizing: border-box;
}

.chart-card {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  margin-bottom: 16px;
  height: 380px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.chart-card-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
  background-color: #fafafa;
}

.chart-card-subtitle {
  font-size: 12px;
  color: #909399;
  margin-left: 8px;
}

.chart-card .chart-container-wrapper {
  flex: 1;
  padding: 0;
  overflow: hidden;
}

/* 统计分析区域样式 */
.statistics-area {
  margin-bottom: 16px;
  background-color: #fff;
  padding: 16px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.statistics-area .statistics-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 12px;
}

.statistics-area .statistics-header h3 {
  margin: 0;
  font-size: 18px;
  color: #303133;
  font-weight: 500;
}

.statistics-area .statistics-controls {
  display: flex;
  align-items: center;
}

.statistics-area .statistics-controls .ant-radio-group {
  margin-right: 8px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .table-operator {
    display: flex;
    flex-direction: column;
  }

  .table-operator button {
    margin-bottom: 8px;
  }
}

/* 过渡动画 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s, max-height 0.5s;
  max-height: 1500px;
  overflow: hidden;
}
.fade-enter,
.fade-leave-to {
  opacity: 0;
  max-height: 0;
}
</style> 